package com.jslx.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created by ydw on 2017/7/22.
 */
@Component
public class RedisTools {
    @Autowired
    private StringRedisTemplate stringRedisTemplate; //1

    @Resource(name="stringRedisTemplate")
    ValueOperations<String,String> valOpsStr;

    public void remove(String ...keys){
        for (String key : keys) {
            remove(key);
        }
    }

    public void remove(String key){
        if (isKeyExists(key)) {
            stringRedisTemplate.delete(key);
        }

    }

    public boolean isKeyExists(String key){
        return stringRedisTemplate.hasKey(key);
    }

    public String getValue(String key){
        String s = valOpsStr.get(key);
        return s;
    }

    public boolean setForever(String key,String value){
        boolean result=false;
        try {
            valOpsStr.set(key,value);
            result=true;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return result;
    }

    /**
     *
     * @param key
     * @param value
     * @param expireTime  过期时间，单位（秒）
     * @return
     */
    public boolean setByTime(String key ,String value,Long expireTime){
        boolean result=false;
        try {
            valOpsStr.set(key,value,expireTime, TimeUnit.SECONDS);
            result=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
